package com.polaris.live.viewmodel.home

import androidx.lifecycle.MutableLiveData
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.net.homeService
import com.polaris.live.net.liveService
import com.polaris.live.resp.back_resp.HonorRankResp
import com.polaris.live.resp.back_resp.PartyRoomResp
import com.polaris.live.resp.back_resp.RegionDataResp
import com.polaris.live.resp.base.ListResp
import com.polaris.live.resp.base.new
import com.polaris.live.resp.bean.FriendTopBean
import com.polaris.live.utils.CommonUtils
import kotlinx.coroutines.coroutineScope

/**
 * FriendShipViewModel
 *
 * @author Created by 半仙 on 2024/8/30/030 20:00
 */
class FriendShipViewModel : BaseViewModel() {

    private var mIsFriendReq = true//是否第一次请求

    var mPageNumber = 0//页码

    val mListLiveData = MutableLiveData<ResultState<ListResp<Any>>>()//用户数据

    val mHonorLiveData = MutableLiveData<ResultState<List<HonorRankResp>>>()//banner

    val mRegionLiveData = MutableLiveData<RegionDataResp>()//区域数据

    private fun getChatPartyData(position: Int, filterRegion: Int? = null) {
        if (position == 0) {
            //请求轮播图
            request({ homeService.getHonorRanks() }, mHonorLiveData)
            //请求数据
            request({
                coroutineScope {
                    //先获取区域然后得到默认选中的   再去请求列表
                    val region = homeService.getResourceRegion()
                    val default = region.result?.regions?.find { it.region == region.result?.default }
                    val tempRegion = if (mIsFriendReq) {
                        default?.region
                    } else {
                        filterRegion
                    }
                    //得到了默认值开始请求列表
                    val listResp = homeService.getChatParty(position, filterRegion = tempRegion)
                    //判断是否大于等于4个  如果是则展示大item
                    var userList = listResp.result?.list?.toMutableList()
                    var friendTopBean: FriendTopBean? = null
                    if (!userList.isNullOrEmpty()) {
                        if (userList.size >= 4) {
                            friendTopBean = FriendTopBean(userList[0], userList[1], userList[2])
                            repeat(3) { userList.removeAt(0) }//去掉前三个元素
                        }
                    }
                    //数值游戏插到集合里
                    val newList =
                        CommonUtils.extGameDealWith(listResp.ext, userList ?: emptyList(), friendTopBean != null)

                    val list = buildList<Any> {
                        region.result?.let { add(it) }
                        friendTopBean?.let { add(friendTopBean) }
                        addAll(newList)
                    }

                    listResp.new(list)
                }
            }, {
                mIsFriendReq = false
                // 找到并提取区域选择数据
                val updatedList = it.list.toMutableList() // 转换为可变列表
                updatedList
                    .indexOfFirst { item -> item is RegionDataResp } // 找到 RegionDataResp 的索引
                    .takeIf { index -> index != -1 } // 如果索引有效，继续处理
                    ?.let { index ->
                        (updatedList.removeAt(index) as? RegionDataResp)?.also { region ->
                            mRegionLiveData.value = region // 更新区域选择 LiveData
                        }
                    }

                // 更新剩余列表数据到 mListLiveData
                mListLiveData.value = ResultState.onAppSuccess(it.copy(list = updatedList))
            }, {
                val error = if (it is AppException) {
                    it
                } else {
                    AppException(500, it.message ?: "network error")
                }
                mListLiveData.value = ResultState.onAppError(error)
            })
        } else {
            request({
                coroutineScope {
                    val listResp = homeService.getChatParty(position, filterRegion = filterRegion)

                    val newList = CommonUtils.extGameDealWith(listResp.ext, listResp.result?.list ?: emptyList())

                    listResp.new(newList)
                }
            }, {
                mListLiveData.value = ResultState.onAppSuccess(it.new(it.list))
            }, {
                val error = if (it is AppException) {
                    it
                } else {
                    AppException(500, it.message ?: "network error")
                }
                mListLiveData.value = ResultState.onAppError(error)
            })
        }
    }

    /**
     * 获取房间信息
     */
    val mPartyRoomLiveData = MutableLiveData<ResultState<PartyRoomResp>>()
    fun getPartyRoom() {
        request({ liveService.getPartyRoom() }, mPartyRoomLiveData)
    }

    fun onGoRefresh(region: Int?) {
        mPageNumber = 0
        getChatPartyData(mPageNumber, region)
    }

    fun onGoLoadMore(region: Int?) {
        mPageNumber += 1
        getChatPartyData(mPageNumber, region)
    }
}